package com.yao.system.OSS;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

public class AliOSSUtil {

    private static final String imgPrefix = "img/";
    private static final String otherPrefix = "other/";

    public static String upload(MultipartFile multipartFile) throws IOException {
        InputStream inputStream = multipartFile.getInputStream();
        String originalFilename = multipartFile.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = UUID.randomUUID().toString() + suffix;

        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKey, accessKeySecret);
        PutObjectResult result = ossClient.putObject(bucketName, imgPrefix + fileName, inputStream);

        String url = endpoint.split("//")[0] + "//" + bucketName + "." +
                endpoint.split("//")[1] + "/" + imgPrefix + fileName;

        ossClient.shutdown();
        return url;
    }































    /**
     * 注意此处的阿里accessKey和KeySecret为本人阿里云账号私有
     * 为以防被盗用，本次作业结束后将进行删除修改
     * 没有accessKey和KeySecret将无法使用阿里云OSS对象存储服务
     * 若想实现该文件上传功能，请使用自己的阿里云OSS服务
     * ------- 2024.4.30
     * ------- 巢湖学院 霖
     * 五一放假万岁！！！！
     */

    private static final String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
    private static final String accessKey = "LTAI5tPBoU2nUiJ7dWxUJAhG";
    private static final String accessKeySecret = "XF1WyqZIDPrjJws0f4kEHEuHE7WkpL";
    private static final String bucketName = "yao-ossbucket";

}
